<template>
  <div class="lottery-bg">
    <div class="lottery-center">
      <div class="lottery-card">
        <div class="lottery-header">
          <div class="lottery-tabs">
            <button :class="{active: tab==='lottery'}" @click="tab='lottery'">幸运抽奖</button>
          </div>
          <div class="lottery-icons">
            <el-icon><i class="fas fa-gift"></i></el-icon>
          </div>
        </div>

        <el-form :model="form" status-icon class="username-form" @submit.prevent>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名" clearable @keyup.enter="draw" />
          </el-form-item>
        </el-form>

        <!-- 九宫格抽奖区域 -->
        <div class="lottery-grid">
          <div
              v-for="(prize, index) in displayedPrizes"
              :key="index"
              class="grid-item"
              :class="{
              active: activeIndex === index,
              center: index === 4
            }"
          >
            <div class="prize-content">
              <div class="prize-icon">
                <el-icon v-if="getPrizeIcon(index)"><component :is="getPrizeIcon(index)" /></el-icon>
                <span v-else>{{ getPrizeEmoji(prize.name) }}</span>
              </div>
              <div class="prize-name">{{ prize.name }}</div>
            </div>
          </div>
        </div>

        <el-button
            type="primary"
            @click="draw"
            :loading="rolling"
            :disabled="rolling"
            class="draw-button"
        >
          {{ rolling ? '抽奖中...' : '开始抽奖' }}
        </el-button>

        <!-- 中奖提示弹窗 -->
        <div v-if="showWinPopup" class="win-popup" :class="{ 'win-animation': winPopupAnimation }">
          <div class="win-content">
            <div class="win-header">
              <el-icon class="win-icon"><Trophy /></el-icon>
              <h2>{{ winSuccess ? '恭喜中奖!' : '很遗憾' }}</h2>
            </div>
            <div class="win-message">
              <p>{{ winMessage }}</p>
            </div>
            <div class="win-actions">
              <el-button @click="closeWinPopup" type="primary" round>确定</el-button>
            </div>
          </div>
        </div>

        <!-- 原始提示 -->
        <el-alert
            v-if="msg && !showWinPopup"
            :title="msg"
            :type="msgType"
            show-icon
            class="lottery-alert"
        />

        <div class="lottery-link">
          <el-link type="primary" @click="$emit('to-wins')" underline="never">查看中奖信息</el-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '../api/request'
import {
  Present,
  Monitor,
  Ticket,
  Coffee,
  MagicStick,
  Apple,
  Cherry,
  Grape,
  Orange,
  Trophy
} from '@element-plus/icons-vue'

const displayedPrizes = ref([
  { id: 1, name: '欧洲十日游' },
  { id: 2, name: 'RTX5090' },
  { id: 3, name: '现金1万元' },
  { id: 4, name: '咖啡机' },
  { id: 5, name: '再抽一次' },
  { id: 6, name: '苹果手机' },
  { id: 7, name: '樱桃一箱' },
  { id: 8, name: '现金100元' },
  { id: 9, name: '橙子一箱' }
])

const form = ref({ username: '' })
const msg = ref('')
const msgType = ref('success')
const rolling = ref(false)
const activeIndex = ref(0)
const allPrizes = ref([])
let timer = null
let flashTimer = null

// 中奖弹窗相关
const showWinPopup = ref(false)
const winSuccess = ref(false)
const winMessage = ref('')
const winPopupAnimation = ref(false)

// 获取奖品图标
const getPrizeIcon = (index) => {
  const icons = [Present, Monitor, Ticket, Coffee, MagicStick, Apple, Cherry, Grape, Orange]
  return icons[index]
}

// 获取奖品emoji
const getPrizeEmoji = (name) => {
  const emojiMap = {
    '欧洲十日游': '✈️',
    'RTX5090': '💻',
    '现金1万元': '💰',
    '咖啡机': '☕',
    '再抽一次': '🔄',
    '苹果手机': '📱',
    '樱桃一箱': '🍒',
    '现金100元': '💵',
    '橙子一箱': '🍊'
  }
  return emojiMap[name] || '🎁'
}

// 关闭中奖弹窗
const closeWinPopup = () => {
  winPopupAnimation.value = false
  setTimeout(() => {
    showWinPopup.value = false
  }, 300)
}

// 从后端加载奖品数据
const loadPrizes = async () => {
  try {
    const res = await request.get('/lottery/prizes')
    allPrizes.value = res.data
    if (res.data.length >= 9) {
      displayedPrizes.value = res.data.slice(0, 9)
    } else if (res.data.length > 0) {
      const filledPrizes = [...res.data]
      while (filledPrizes.length < 9) {
        filledPrizes.push(...res.data)
      }
      displayedPrizes.value = filledPrizes.slice(0, 9)
    }
  } catch (e) {
    console.error('加载奖品数据失败:', e)
  }
}

// 抽奖逻辑
const draw = async () => {
  if (!form.value.username) {
    msg.value = '请输入用户名'
    msgType.value = 'warning'
    return
  }

  msg.value = ''
  rolling.value = true
  if (timer) clearInterval(timer)
  if (flashTimer) clearInterval(flashTimer)

  let count = 0
  const sequence = [0, 1, 2, 5, 8, 7, 6, 3]
  let seqIndex = 0

  timer = setInterval(() => {
    activeIndex.value = sequence[seqIndex]
    seqIndex = (seqIndex + 1) % sequence.length
    count++
    if (count > 20) {
      clearInterval(timer)
      timer = setInterval(() => {
        activeIndex.value = sequence[seqIndex]
        seqIndex = (seqIndex + 1) % sequence.length
        count++
        if (count > 30) {
          clearInterval(timer)
          timer = setInterval(() => {
            activeIndex.value = sequence[seqIndex]
            seqIndex = (seqIndex + 1) % sequence.length
          }, 150)
        }
      }, 100)
    }
  }, 200)

  try {
    const res = await request.post(`/lottery/draw?username=${form.value.username}`)
    let prizeName = '谢谢参与'
    if (res.data.success) {
      const match = res.data.message.match(/：(.+)$/)
      if (match) prizeName = match[1]
    }

    setTimeout(() => {
      clearInterval(timer)
      let winIndex = 8
      for (let i = 0; i < displayedPrizes.value.length; i++) {
        if (displayedPrizes.value[i].name === prizeName) {
          winIndex = i
          break
        }
      }
      activeIndex.value = winIndex
      rolling.value = false
      msg.value = res.data.message
      msgType.value = res.data.success ? 'success' : 'info'
      winSuccess.value = res.data.success
      winMessage.value = res.data.message
      showWinPopup.value = true
      setTimeout(() => {
        winPopupAnimation.value = true
      }, 50)

      if (res.data.success && winIndex !== 4) {
        let flashCount = 0
        flashTimer = setInterval(() => {
          const item = document.querySelector(`.grid-item:nth-child(${winIndex + 1})`)
          if (item) item.classList.toggle('flashing')
          flashCount++
          if (flashCount > 8) {
            clearInterval(flashTimer)
            if (item) item.classList.remove('flashing')
          }
        }, 300)
      }
    }, 3000)
  } catch (e) {
    clearInterval(timer)
    if (flashTimer) clearInterval(flashTimer)
    rolling.value = false
    msg.value = '抽奖失败'
    msgType.value = 'error'
    winSuccess.value = false
    winMessage.value = '抽奖失败，请稍后重试'
    showWinPopup.value = true
    setTimeout(() => {
      winPopupAnimation.value = true
    }, 50)
  }
}

onMounted(() => {
  loadPrizes()
})

const tab = ref('lottery')
</script>

<style scoped>
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css');

.lottery-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #fff5e6 0%, #ffe6cc 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

.lottery-center {
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
}

.lottery-card {
  background: rgba(255, 255, 255, 0.92);
  border-radius: 24px;
  box-shadow: 0 15px 35px rgba(255, 153, 95, 0.2);
  padding: 40px 35px 30px;
  width: 420px;
  max-width: 95vw;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 184, 108, 0.3);
  position: relative;
  overflow: hidden;
}

.lottery-card::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255, 184, 108, 0.15) 0%, transparent 70%);
  z-index: -1;
}

.lottery-header {
  text-align: center;
  margin-bottom: 25px;
}

.lottery-tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.lottery-tabs button {
  background: rgba(255, 245, 230, 0.8);
  border: none;
  color: #ff9a3d;
  font-size: 20px;
  padding: 10px 35px;
  border-radius: 25px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s ease;
}

.lottery-tabs .active {
  background: linear-gradient(135deg, #ff9a3d 0%, #ff6a00 100%);
  color: white;
  box-shadow: 0 5px 15px rgba(255, 154, 61, 0.4);
}

.lottery-icons {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  color: #ff9a3d;
  font-size: 32px;
  animation: bounce 2s infinite;
}

@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-10px); }
}

.username-form {
  margin-bottom: 25px;
}

:deep(.el-form-item__label) {
  color: #666;
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  background: rgba(255, 245, 230, 0.6);
  border-radius: 10px;
  border: 1px solid rgba(255, 184, 108, 0.5);
  color: #333;
  box-shadow: none;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  border-color: rgba(255, 154, 61, 0.8);
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #ff9a3d;
  box-shadow: 0 0 0 2px rgba(255, 154, 61, 0.2);
}

:deep(.el-input__inner) {
  color: #333;
  background: transparent;
}

/* 九宫格样式 */
.lottery-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 12px;
  margin: 25px 0;
  perspective: 1000px;
}

.grid-item {
  aspect-ratio: 1;
  background: linear-gradient(135deg, #fff5e6 0%, #ffe6cc 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(255, 153, 95, 0.2);
  border: 1px solid rgba(255, 184, 108, 0.5);
}

.grid-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(255, 184, 108, 0.1) 0%, transparent 100%);
  z-index: 1;
}

.grid-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(255, 153, 95, 0.3);
  border-color: rgba(255, 154, 61, 0.8);
}

.grid-item.active {
  background: linear-gradient(135deg, #ff9a3d 0%, #ff6a00 100%);
  transform: scale(1.05);
  box-shadow: 0 0 20px rgba(255, 154, 61, 0.6);
  z-index: 2;
}

.grid-item.center {
  background: linear-gradient(135deg, #ffcc00 0%, #ff9900 100%);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { box-shadow: 0 0 10px rgba(255, 204, 0, 0.5); }
  50% { box-shadow: 0 0 25px rgba(255, 204, 0, 0.8); }
  100% { box-shadow: 0 0 10px rgba(255, 204, 0, 0.5); }
}

.grid-item.flashing {
  animation: flash 0.3s infinite;
}

@keyframes flash {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.prize-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 10px;
  z-index: 2;
}

.prize-icon {
  font-size: 24px;
  margin-bottom: 8px;
  color: #ff9a3d;
}

.grid-item.active .prize-icon {
  color: white;
  text-shadow: 0 0 10px rgba(255, 255, 255, 0.7);
}

.prize-name {
  font-size: 12px;
  font-weight: 500;
  color: #666;
  line-height: 1.3;
}

.grid-item.active .prize-name {
  color: white;
  font-weight: 600;
}

.draw-button {
  background: linear-gradient(135deg, #ff9a3d 0%, #ff6a00 100%);
  border: none;
  color: white;
  font-weight: bold;
  letter-spacing: 1px;
  width: 100%;
  padding: 16px;
  font-size: 18px;
  border-radius: 12px;
  margin: 15px 0;
  transition: all 0.3s ease;
  box-shadow: 0 5px 15px rgba(255, 154, 61, 0.4);
}

.draw-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(255, 154, 61, 0.6);
}

.draw-button:disabled {
  opacity: 0.7;
}

/* 中奖弹窗样式 */
.win-popup {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.win-popup.win-animation {
  opacity: 1;
}

.win-content {
  background: linear-gradient(135deg, #fff5e6 0%, #ffe6cc 100%);
  border-radius: 20px;
  padding: 40px 30px;
  width: 90%;
  max-width: 400px;
  text-align: center;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
  transform: scale(0.8);
  transition: transform 0.3s ease;
  border: 2px solid rgba(255, 154, 61, 0.5);
  position: relative;
  overflow: hidden;
}

.win-popup.win-animation .win-content {
  transform: scale(1);
}

.win-content::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255, 184, 108, 0.2) 0%, transparent 70%);
  animation: rotate 10s linear infinite;
  z-index: -1;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.win-header {
  margin-bottom: 25px;
}

.win-icon {
  font-size: 60px;
  color: #ffcc00;
  margin-bottom: 15px;
  animation: win-icon-pulse 1.5s infinite;
}

@keyframes win-icon-pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}

.win-header h2 {
  color: #333;
  font-size: 28px;
  margin: 0 0 10px;
  text-shadow: 0 0 10px rgba(255, 204, 0, 0.5);
}

.win-message p {
  color: #666;
  font-size: 18px;
  line-height: 1.5;
  margin: 0;
}

.win-success .win-header h2 {
  color: #ff9a3d;
}

.win-success .win-icon {
  color: #ffcc00;
  text-shadow: 0 0 20px rgba(255, 204, 0, 0.8);
}

.win-actions {
  margin-top: 30px;
}

.win-actions .el-button {
  background: linear-gradient(135deg, #ff9a3d 0%, #ff6a00 100%);
  border: none;
  color: white;
  font-size: 16px;
  font-weight: bold;
  padding: 12px 30px;
  box-shadow: 0 5px 15px rgba(255, 154, 61, 0.4);
}

.win-actions .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(255, 154, 61, 0.6);
}

.lottery-alert {
  margin-top: 15px;
  border-radius: 10px;
  border: none;
  background: rgba(255, 245, 230, 0.6);
  border: 1px solid rgba(255, 184, 108, 0.5);
}

.lottery-link {
  margin-top: 15px;
  text-align: center;
}

:deep(.el-link) {
  color: #ff9a3d;
  font-weight: 500;
}

:deep(.el-link:hover) {
  color: #ff6a00;
}

@media (max-width: 480px) {
  .lottery-card {
    padding: 30px 20px;
  }

  .lottery-tabs button {
    padding: 8px 20px;
    font-size: 18px;
  }
}
</style>